<template>
  <div class="container">
    <div class="form-content">
      <a-form layout="inline">
        <a-form-item label="职位状态">
          <a-select
            placeholder="请选择职位状态"
            v-model:value="status"
            style="width: 150px"
            allowClear
          >
            <a-select-option :value="0">已创建</a-select-option>
            <a-select-option :value="1">已发布</a-select-option>
            <a-select-option :value="2">已暂停</a-select-option>
            <a-select-option :value="3">已关闭</a-select-option>
            <a-select-option :value="4">已招满</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="起止时间">
          <a-range-picker v-model:value="dataRange" />
        </a-form-item>
        <a-form-item label="工作地">
          <a-input placeholder="请输入工作地" style="width: 150px" v-model:value="data" />
        </a-form-item>
        <a-form-item label="职位标签">
          <a-select
            allowClear
            v-model:value="tag"
            mode="multiple"
            style="width: 150px"
            placeholder="请选择职位标签"
            :options="tags"
          ></a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" class="search-botton" @click="search">搜索</a-button>
          <a-button @click="reset">重置</a-button>
        </a-form-item>
      </a-form>
      <div>
        <a-radio-group v-model:value="store.positionFlag" style="margin-right: 12px">
          <a-radio-button :value="true">我的职位</a-radio-button>
          <a-radio-button :value="false">所有职位</a-radio-button>
        </a-radio-group>
        <a-button type="primary" @click="handleAddPosition">添加职位</a-button>
      </div>
    </div>
    <div class="table-content">
      <a-table
        class="table"
        :columns="columns"
        :data-source="store.positionList"
        :loading="store.loading"
        :scroll="{ x: 1500, y: 650 }"
        :pagination="false"
      >
        <template #bodyCell="{ column, record }">
          <div v-if="column.key === 'operation'">
            <a-popconfirm
              title="确认发布当前职位？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleRelease(record)"
            >
              <a-button type="link" size="small">发布</a-button>
            </a-popconfirm>
            <a-button type="link" size="small" @click="handleEdit(record)">编辑</a-button>
            <a-button type="link" size="small" @click="handleDetail(record)">详情</a-button>
            <a-popconfirm
              title="确认删除当前职位？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record)"
            >
              <a-button type="link" size="small">删除</a-button>
            </a-popconfirm>
          </div>
          <div v-else-if="column.key === 'requirementList'">
            <span v-for="item in record.requirement" :key="item">{{ item }} <br /></span>
          </div>
          <div v-else-if="column.key === 'tagList'">
            <a-tag
              style="margin-top: 4px; margin-right: 8px"
              color="green"
              v-for="item in record.tags"
              :key="item"
              >{{ item }}</a-tag
            >
          </div>
        </template>
      </a-table>
    </div>
    <div class="page-content">
      <a-pagination
        v-if="store.total > 0"
        v-model:page-size="store.pageSize"
        :page-size-options="['10', '20', '50']"
        :total="store.total"
        :show-total="total => `共 ${total} 条`"
        show-size-changer
        @change="onPageChange"
      >
      </a-pagination>
    </div>
  </div>
  <info-drawer></info-drawer>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { usePositionStore } from '@/stores/positionStore'
import { useUserStore } from '@/stores/userStore'
import infoDrawer from './components/infoDrawer.vue'
import server from '@/api/index'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

const store = usePositionStore()
const userStore = useUserStore()

const positionFlag = ref(true)

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 100,
    fixed: 'left',
  },
  {
    title: '职位名称',
    dataIndex: 'title',
    key: 'title',
    width: 100,
    fixed: 'left',
  },
  {
    title: '薪资',
    dataIndex: 'salary',
    key: 'salary',
    width: 150,
  },
  {
    title: '工作地',
    dataIndex: 'location',
    key: 'location',
    width: 150,
  },
  {
    title: '应往届',
    dataIndex: 'gen',
    key: 'gen',
    width: 150,
  },
  {
    title: '教育背景',
    dataIndex: 'bg',
    key: 'bg',
    width: 150,
  },
  {
    title: '需求列表',
    dataIndex: 'requirementList',
    key: 'requirementList',
    width: 300,
  },
  {
    title: '描述',
    dataIndex: 'description',
    key: 'description',
    width: 150,
  },
  {
    title: '起止时间',
    dataIndex: 'duration',
    key: 'duration',
    width: 220,
  },
  {
    title: '职位状态',
    dataIndex: 'status',
    key: 'status',
    width: 150,
  },
  {
    title: '职位标签',
    dataIndex: 'tagList',
    key: 'tagList',
    width: 150,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 220,
    fixed: 'right',
  },
]

const tags = ref([
  {
    value: 'Java',
    label: 'Java',
  },
  {
    value: 'Python',
    label: 'Python',
  },
  {
    value: 'C++',
    label: 'C++',
  },
  {
    value: '前端开发',
    label: '前端开发',
  },
  {
    value: '后端开发',
    label: '后端开发',
  },
])

const data = ref('')
const dataRange = ref([])
const tag = ref([])
const status = ref()

// 格式化日期
const formatDateRange = (startDate, endDate) => {
  const formattedStart = dayjs(startDate).format('YYYY/MM/DD')
  const formattedEnd = dayjs(endDate).format('YYYY/MM/DD ')
  return `${formattedStart}至${formattedEnd}`
}

const search = async () => {
  try {
    store.page = 1
    if (store.positionFlag) {
      const res = await server.getlistMyPostVOByPage({
        userId: userStore.userAccount,
        startDate: dataRange.value?.[0]?.format('YYYY/MM/DD HH:mm:ss'),
        endDate: dataRange.value?.[1]?.format('YYYY/MM/DD HH:mm:ss'),
        tags: tag.value,
        location: data.value,
        status: status.value,
        current: store.page,
        pageSize: store.pageSize,
      })
      if (res.data.code === 0) {
        store.total = res.data.data.total
        store.positionList = res.data.data.records

        store.positionList.forEach(item => {
          if (item.startDate && item.endDate) {
            item.duration = formatDateRange(item.startDate, item.endDate)
          } else {
            item.duration = ''
          }
          switch (item.status) {
            case 0:
              item.status = '已创建'
              break
            case 1:
              item.status = '已发布'
              break
            case 2:
              item.status = '已暂停'
              break
            case 3:
              item.status = '已关闭'
              break
            case 4:
              item.status = '已招满'
              break
          }
        })
      } else {
        message.error(`搜索职位时发生错误: ${res.data.message}`)
      }
    } else {
      const res = await server.getlistPostVOByPage({
        location: data.value,
        startDate: dataRange.value?.[0]?.format('YYYY/MM/DD HH:mm:ss'),
        endDate: dataRange.value?.[1]?.format('YYYY/MM/DD HH:mm:ss'),
        tags: tag.value,
        status: status.value,
        current: store.page,
        pageSize: store.pageSize,
      })
      if (res.data.code === 0) {
        store.total = res.data.data.total
        store.positionList = res.data.data.records

        store.positionList.forEach(item => {
          if (item.startDate && item.endDate) {
            item.duration = formatDateRange(item.startDate, item.endDate)
          } else {
            item.duration = ''
          }
          switch (item.status) {
            case 0:
              item.status = '已创建'
              break
            case 1:
              item.status = '已发布'
              break
            case 2:
              item.status = '已暂停'
              break
            case 3:
              item.status = '已关闭'
              break
            case 4:
              item.status = '已招满'
              break
          }
        })
      } else {
        message.error(`搜索职位时发生错误: ${res.data.message}`)
      }
    }
  } catch (e) {
    console.log(e)
    message.error(`搜索职位时发生错误: ${e.message}`)
  }
}
const reset = () => {
  tag.value = []
  status.value = ''
  data.value = []
  dataRange.value = []
  if (store.positionFlag) {
    getMyPositionList()
  } else {
    getAllPositionList()
  }
}
const handleRelease = async item => {
  try {
    const res = await server.releasePosition({ id: item.id })
    if (res.data.code === 0) {
      message.success(res.data.message)
      if (store.positionFlag) {
        getMyPositionList()
      } else {
        getAllPositionList()
      }
    } else {
      message.error(`发布职位失败: ${res.data.message}`)
    }
  } catch (e) {
    console.log(e)
    message.error(`发布职位时发生错误: ${e.message}`)
  }
}
const handleEdit = item => {
  store.addFlag = false
  store.editFlag = true
  store.openDrawer = true
  store.editData = item
  store.title = '编辑职位'
}
const handleDetail = item => {
  store.editFlag = false
  store.openDrawer = true
  store.editData = item
}
const handleDelete = async item => {
  try {
    const res = await server.deletePosition({
      id: item.id,
      userId: userStore.userAccount,
    })
    if (res.data.code === 0) {
      message.success(res.data.message)
      if (store.positionFlag) {
        getMyPositionList()
      } else {
        getAllPositionList()
      }
    } else {
      message.error(`删除职位失败: ${res.data.message}`)
    }
  } catch (e) {
    message.error(`删除职位时发生错误: ${e.message}`)
  }
}
// 分页器处理
const onPageChange = async (page, pageSize) => {
  store.page = page
  store.pageSize = pageSize
  if (store.positionFlag.value) {
    getMyPositionList()
  } else {
    getAllPositionList()
  }
}
const handleAddPosition = () => {
  store.addFlag = true
  store.editFlag = true
  store.openDrawer = true
  store.editData = {}
  store.title = '新建职位'
}
// 获取当前hr列表
const getMyPositionList = async () => {
  try {
    let params = {
      userId: userStore.userAccount,
      pageSize: store.pageSize,
      current: store.page,
    }
    const res = await server.getlistMyPostVOByPage(params)
    if (res.data.code === 0) {
      store.total = res.data.data.total
      store.positionList = res.data.data.records
      console.log(store.positionList)
      store.positionList.forEach(item => {
        if (item.startDate && item.endDate) {
          item.duration = formatDateRange(item.startDate, item.endDate)
        } else {
          item.duration = ''
        }
        switch (item.status) {
          case 0:
            item.status = '已创建'
            break
          case 1:
            item.status = '已发布'
            break
          case 2:
            item.status = '已暂停'
            break
          case 3:
            item.status = '已关闭'
            break
          case 4:
            item.status = '已招满'
            break
        }
      })
    } else {
      message.error(`获取我的职位列表失败: ${res.data.message}`)
    }
  } catch (e) {
    message.error(`获取我的职位列表时发生错误: ${e.message}`)
  }
}
// 获取全部状态下列表
const getAllPositionList = async () => {
  try {
    let params = {
      pageSize: store.pageSize,
      current: store.page,
    }
    const res = await server.getlistPostVOByPage(params)
    if (res.data.code === 0) {
      store.total = res.data.data.total
      store.positionList = res.data.data.records

      store.positionList.forEach(item => {
        if (item.startDate && item.endDate) {
          item.duration = formatDateRange(item.startDate, item.endDate)
        } else {
          item.duration = ''
        }
        switch (item.status) {
          case 0:
            item.status = '已创建'
            break
          case 1:
            item.status = '已发布'
            break
          case 2:
            item.status = '已暂停'
            break
          case 3:
            item.status = '已关闭'
            break
          case 4:
            item.status = '已招满'
            break
        }
      })
    } else {
      message.error(`获取所有职位列表失败: ${res.data.message}`)
    }
  } catch (e) {
    message.error(`获取所有职位列表时发生错误: ${e.message}`)
  }
}
// 获取状态枚举
const getStatusEnums = async () => {
  try {
    const res = await server.getPositionStatusEnums()
    if (res.data.code === 0) {
      const temp = Object.values(res.data.data)
      for (let i = 2; i < temp.length; i++) {
        store.statusEnums.push({ label: temp[i], value: temp[i] })
      }
    } else {
      message.error(`获取职位状态枚举失败: ${res.data.message}`)
    }
  } catch (e) {
    message.error(`获取职位状态枚举时发生错误: ${e.message}`)
  }
}
watch(
  () => store.positionFlag,
  val => {
    if (val) {
      getMyPositionList()
      // 获取个人数据接口
    } else {
      getAllPositionList()
      // 获取所有数据
    }
  },
)

onMounted(() => {
  getStatusEnums()
  getMyPositionList()
})
</script>

<style lang="scss" scoped>
.container {
  // display: flex;
  width: 100%;
  height: 100%;
  background-color: #fff;

  .form-content {
    display: flex;
    justify-content: space-between;
    padding: 20px 20px 0;

    .search-botton {
      margin-right: 10px;
    }
  }

  .table-content {
    padding: 15px;
  }

  .page-content {
    display: flex;
    justify-content: flex-end;
    padding-right: 15px;
  }
}
</style>
